//
//  AY_ReadViewController.m
//  AiYue
//
//  Created by mac on 2023/10/17.
//

#import "AY_ReadViewController.h"
#import <CoreText/CoreText.h>
#import "AY_BatteryView.h"
#import "AY_MaYunView.h"

@interface SXReadView : UIView
@property (nonatomic,strong) NSAttributedString *attributeString;
@end

@implementation SXReadView

-(void)setAttributeString:(NSAttributedString *)attributeString
{
    _attributeString = attributeString;
    [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect
{
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) self.attributeString);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
    CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    //    if (self.mirror) {
    //        CGContextTranslateCTM(ctx, self.bounds.size.width,0);
    //        CGContextScaleCTM(ctx, -1.0, 1.0);
    //    }
    CGPathRef pathRef = CGPathCreateWithRect(self.bounds, NULL);
    CTFrameRef frameRef = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), pathRef, NULL);
    CTFrameDraw(frameRef, ctx);
    
    CFRelease(frameRef);
    CGPathRelease(pathRef);
    CFRelease(frameSetter);
}

@end


@interface SXReadProxy : NSProxy
@property (nonatomic, weak) id obj;
@end

@implementation SXReadProxy
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSMethodSignature *sig;
    sig = [self.obj methodSignatureForSelector:aSelector];
    return sig;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    [invocation invokeWithTarget:self.obj];
}
@end

@interface AY_ReadViewController ()
@property (nonatomic,strong) UILabel *charpterLabel;
@property (nonatomic,strong) SXReadView *readView;
@property (nonatomic,strong) AY_BatteryView *battery;
@property (nonatomic,strong) UILabel *progressLabel;
@property (nonatomic,strong) UILabel *timeLabel;
@property (nonatomic,strong) UIView *backgroundImageView;
@property (nonatomic,strong) UIView *coverBackgroundImageVIew;
@property (nonatomic, strong) SXReadProxy *proxy;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) BOOL is12Hour;

@property (nonatomic,assign) NSInteger page;
@property (nonatomic,assign) NSInteger charpterIndex;

@property (nonatomic,strong) NSAttributedString *content;
@property (nonatomic,strong) NSString *charpter;
@property (nonatomic,assign) NSInteger totalPage;
@property (nonatomic,assign) NSInteger totalCharpter;
@property (nonatomic,strong) UITapGestureRecognizer *tap;
@property (nonatomic,strong) UIPanGestureRecognizer *ges;
@property (nonatomic,strong) AY_MaYunView *mayunView;
@end

@implementation AY_ReadViewController
- (instancetype)init {
    self = [super init];
    if (self){
        self.proxy = [SXReadProxy alloc];
        self.proxy.obj = self;
        self.is12Hour = [self is12HourFormat];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeBatteryLevel:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self.proxy selector:@selector(setTimer) userInfo:nil repeats:YES];
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navBarAlpha = 0;
    self.gk_navLeftBarButtonItem = nil;
    [self.view addSubview:self.backgroundImageView];
    [self.backgroundImageView addSubview:self.charpterLabel];
    [self.backgroundImageView addSubview:self.battery];
    [self.backgroundImageView addSubview:self.progressLabel];
    [self.backgroundImageView addSubview:self.timeLabel];
    [self.backgroundImageView addSubview:self.readView];
    [self.backgroundImageView addSubview:self.coverBackgroundImageVIew];
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    [self.view addSubview:self.mayunView];
    
    [self loadUser];
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self.view addGestureRecognizer:self.tap];
    [self setColors];
    if ([AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 0 || [AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 2 || [AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 4 || [AYMMKV getInt32ForKey:ReadFanYe defaultValue:1] == 1) {
        self.ges = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
        [self.view addGestureRecognizer:self.ges];
    }
}

- (void)loadUser {
    [AYApiRequest getUserInfoSuccess:^(AY_UserModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            [self.mayunView sendPrice:self.bookContentModel.payInfo.price andMyBalance:pkg.data.beanNum andBookId:self.articleid];
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)setColors {
    _progressLabel.textColor = COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]);
    _charpterLabel.textColor = COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]);
    _battery.batteryColor = COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]);
    _timeLabel.textColor = COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]);
    _backgroundImageView.backgroundColor = COLOR([AYMMKV getStringForKey:ReadBackColor defaultValue:@"F6EFDC"]);
    _coverBackgroundImageVIew.backgroundColor = COLOR([AYMMKV getStringForKey:ReadBackColor defaultValue:@"F6EFDC"]);
    
    if ([[AYMMKV getStringForKey:ReadBackColor defaultValue:@"F6EFDC"] isEqual:@"161616"]) {
        [self barStyleLight];
    }else {
        [self barStyleBlack];
    }
    
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithAttributedString:self.content];
    [attributeString addAttribute:NSForegroundColorAttributeName value:COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]) range:NSMakeRange(0, attributeString.length)];
    self.readView.attributeString = attributeString;
    self.content = attributeString.copy;
    
    [self.mayunView updateColors];
}

#pragma mark -- request
//
- (void)pyChaperAction
{
    
}
- (void)showPyView:(BOOL)isShow
{
    self.mayunView.hidden = !isShow;
//    UserBaseData *basedata = [RDConfigModel getModel].userBaseModel;
//    self.shuDouView.charpterModel = self.charpterModel;
//    self.shuDouView.baseData = basedata;
}
//无效果时左右滑动翻页
-(void)pan:(UIPanGestureRecognizer *)ges
{
    //有效滑动距离
    CGFloat distance = 10.f;
    CGPoint translation = [ges translationInView:self.view];
    if (ges.state == UIGestureRecognizerStateEnded) {
        if (translation.x>0 && translation.x>distance) {
            //像右滑动
            if ([self.delegate respondsToSelector:@selector(lastPage:)]) {
                [self.delegate lastPage:self];
            }
        }else if (fabs(translation.x)>distance){
            //向左滑动
            if ([self.delegate respondsToSelector:@selector(nextPage:)]) {
                [self.delegate nextPage:self];
            }
        }
    }
}

-(void)tap:(UITapGestureRecognizer *)tap
{
    CGPoint point = [tap locationInView:self.view];
    CGFloat width = self.view.width/3;
    if(point.x<width){
        if ([self.delegate respondsToSelector:@selector(lastPage:)]) {
            [self.delegate lastPage:self];
        }
    }
    else if (point.x>2*width){
        if ([self.delegate respondsToSelector:@selector(nextPage:)]) {
            [self.delegate nextPage:self];
        }
    }
    else{
        if ([self.delegate respondsToSelector:@selector(invokeMenu:)]) {
            [self.delegate invokeMenu:self];
        }
    }
    
}

-(void)setCharpter:(NSString *)charpter content:(NSAttributedString *)content page:(NSInteger)page totalPage:(NSInteger)totalPage charpterIndex:(NSInteger)chaprterIndex totalCharpter:(NSInteger)totalCharpter
{
    _charpter = charpter;_content = content;_page = page; _totalPage = totalPage; _charpterIndex = chaprterIndex;totalCharpter = _totalCharpter = totalCharpter;
    self.charpterLabel.text = self.charpter;
    self.readView.attributeString = content;
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    CGFloat lastCharpterPercent = chaprterIndex/(CGFloat)totalCharpter;
    
    CGFloat charpterPercent = (chaprterIndex+1)/(CGFloat)totalCharpter;
    
    CGFloat pagePercent = (page+1)/(CGFloat)totalPage;
    
    CGFloat percent = (lastCharpterPercent+(charpterPercent-lastCharpterPercent)*pagePercent)*100;
    
    self.progressLabel.text = [NSString stringWithFormat:@"%.1f%%",percent];
}


-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.charpterLabel.frame = CGRectMake(20, [UIView safeTopBar], self.view.width-40,40 );
    self.battery.frame = CGRectMake(20, 0, self.battery.mj_w, self.battery.mj_h);
    self.timeLabel.frame = CGRectMake(self.battery.right+6, 0, 80, 40);
    self.timeLabel.bottom = self.view.height-[UIView safeBottomBar];
    self.battery.centerY = self.timeLabel.centerY;
    self.progressLabel.frame = CGRectMake(0, self.timeLabel.top, 80, 40);
    self.progressLabel.right = self.view.width-20;
    self.readView.frame = CGRectMake(20, self.charpterLabel.bottom, self.view.width-40, self.timeLabel.top-self.charpterLabel.bottom);
    self.backgroundImageView.frame = self.view.bounds;
    self.coverBackgroundImageVIew.frame = self.view.bounds;
    if (self.isMirror) {
        self.tap.enabled = NO;
        self.ges.enabled = NO;
        CGAffineTransform transform = CGAffineTransformIdentity;
        transform = CGAffineTransformScale(transform, -1, 1);
        self.backgroundImageView.transform = transform;
        self.coverBackgroundImageVIew.alpha = 0.9;
    }else {
        self.ges.enabled = YES;
        self.tap.enabled = YES;
    }
}

- (UILabel *)charpterLabel {
    if (!_charpterLabel){
        _charpterLabel = [[UILabel alloc] init];
        _charpterLabel.font = YFont(14);
    }
    return _charpterLabel;
}

- (AY_BatteryView *)battery {
    if (!_battery){
        _battery = [[AY_BatteryView alloc] initWithFrame:CGRectMake(0, 0, 22, 11)];
        [self setBatteryLevel];
        
    }
    return _battery;
}

- (UILabel *)progressLabel {
    if (!_progressLabel){
        _progressLabel = [[UILabel alloc] init];
        _progressLabel.font = YFont(12);
        _progressLabel.textAlignment = NSTextAlignmentRight;
    }
    return _progressLabel;
}

- (UILabel *)timeLabel {
    if (!_timeLabel){
        _timeLabel = [[UILabel alloc] init];
        _timeLabel.font = YFont(12);
        [self setTimer];
    }
    return _timeLabel;
}

-(SXReadView *)readView
{
    if (!_readView) {
        _readView = [[SXReadView alloc] init];
        _readView.backgroundColor = [UIColor clearColor];
    }
    return _readView;
}

-(UIView *)backgroundImageView
{
    if (!_backgroundImageView) {
        _backgroundImageView = [[UIImageView alloc] init];
    }
    return _backgroundImageView;
}
-(UIView *)coverBackgroundImageVIew
{
    if (!_coverBackgroundImageVIew) {
        _coverBackgroundImageVIew = [[UIImageView alloc] init];
        _coverBackgroundImageVIew.alpha = 0;
    }
    return _coverBackgroundImageVIew;
}
- (AY_MaYunView *)mayunView {
    if (!_mayunView) {
        _mayunView = [[AY_MaYunView alloc] initWithFrame:CGRectMake(0, SCREEN_H - YNUM(400), SCREEN_W, YNUM(350) + GK_TABBAR_HEIGHT)];
    }
    return _mayunView;
}

-(void)setTimer
{
    if (_is12Hour){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.AMSymbol = @"上午";
        dateFormatter.PMSymbol = @"下午";
        [dateFormatter setDateFormat:@"aaah:mm"];
        [dateFormatter setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
        NSString *str = [dateFormatter stringFromDate:[NSDate date]];
        self.timeLabel.text = str;
    } else{
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"H:mm"];
        [dateFormatter setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
        NSString *str = [dateFormatter stringFromDate:[NSDate date]];
        self.timeLabel.text = str;
    }
    
}
- (BOOL)is12HourFormat{
    NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
    NSRange containsA =[formatStringForHours rangeOfString:@"a"];
    BOOL hasAMPM =containsA.location != NSNotFound;
    return hasAMPM;
}
-(void)setBatteryLevel{
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    [self.battery setBatteryValue:(int)(device.batteryLevel*100)];
    
}
-(void)didChangeBatteryLevel:(NSNotification *)notification{
    [self setBatteryLevel];
}
-(void)dealloc{
    [_timer invalidate];
    _timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
